package com.developer.platform.infrastructure.client;

import static com.developer.platform.infrastructure.error.LoginErrorType.ACCOUNT_IS_NULL_ERROR;
import static com.developer.platform.infrastructure.error.LoginErrorType.LOGIN_DP_PHONE_ERROR;

import cn.hutool.core.util.PhoneUtil;
import cn.hutool.http.HttpUtil;
import com.veeker.core.exceptions.BusinessException;
import com.veeker.core.utils.JsonUtils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author ：qiaoliang
 * @date ：2021-01-02
 */
@Component
public class ApiClient {

  private final DapengApi dapengApi;

  public ApiClient(
      DapengApi dapengApi) {
    this.dapengApi = dapengApi;
  }

  public ApiUser login(Object account, Object password){
    Map<String, Object> map = new HashMap<>();
    map.put("source","NORMALLOGIN");
    BusinessException.isFalse(PhoneUtil.isPhone(account.toString()),LOGIN_DP_PHONE_ERROR);
    map.put("account",account);
    map.put("password",password);
    map.put("timestamp", Long.toString(System.currentTimeMillis()));
    map.put("sign", createSign(map,dapengApi.apiKey));
    String body = HttpUtil.post(dapengApi.uri + "/api/user/account/verification", map);
    DapengApiDto dapengApiDto = JsonUtils.toBean(body, DapengApiDto.class);
    BusinessException.isFalse("true".equals(dapengApiDto.getSuccess())
        && "AccountVerification".equals(dapengApiDto.getData().getStatus())
        && dapengApiDto.getData().getUsers().size() > 0, ACCOUNT_IS_NULL_ERROR);
    return dapengApiDto.getData().getUsers().get(0);
  }
  public static class DapengApiDto {
    private String success;
    private String msg;
    private LoginDate data;

    public String getSuccess() {
      return success;
    }

    public void setSuccess(String success) {
      this.success = success;
    }

    public String getMsg() {
      return msg;
    }

    public void setMsg(String msg) {
      this.msg = msg;
    }

    public LoginDate getData() {
      return data;
    }

    public void setData(
        LoginDate data) {
      this.data = data;
    }

    static class LoginDate{
      private String status;
      private String msg;
      private List<ApiUser> users;

      public String getStatus() {
        return status;
      }

      public void setStatus(String status) {
        this.status = status;
      }

      public String getMsg() {
        return msg;
      }

      public void setMsg(String msg) {
        this.msg = msg;
      }

      public List<ApiUser> getUsers() {
        return users;
      }

      public void setUsers(
          List<ApiUser> users) {
        this.users = users;
      }
    }
  }

  public static class ApiUser{
    private String userId;
    private String school;
    private String spare4;
    private String avatar;
    private String nickName;

    public String getUserId() {
      return userId;
    }

    public void setUserId(String userId) {
      this.userId = userId;
    }

    public String getSchool() {
      return school;
    }

    public void setSchool(String school) {
      this.school = school;
    }

    public String getSpare4() {
      return spare4;
    }

    public void setSpare4(String spare4) {
      this.spare4 = spare4;
    }

    public String getAvatar() {
      return avatar;
    }

    public void setAvatar(String avatar) {
      this.avatar = avatar;
    }

    public String getNickName() {
      return nickName;
    }

    public void setNickName(String nickName) {
      this.nickName = nickName;
    }
  }

  public static String createSign(Map<String, Object> params, String aipKey) {

    String[] keys = params.keySet().toArray(new String[params.keySet().size()]);

    Arrays.sort(keys);

    String oldSign = "";
    for (String key : keys) {
      oldSign = oldSign + key + params.get(key);
    }
    oldSign = aipKey + oldSign + aipKey;

    String sign = createMd5(oldSign);
    return sign.toUpperCase();
  }

  public static String createMd5(String oldSign) {
    String result = "";
    try {
      MessageDigest md = MessageDigest.getInstance("MD5");
      md.update(oldSign.getBytes());
      byte b[] = md.digest();
      int i;
      StringBuffer buf = new StringBuffer("");
      for (int offset = 0; offset < b.length; offset++) {
        i = b[offset];
        if (i < 0)
          i += 256;
        if (i < 16)
          buf.append("0");
        buf.append(Integer.toHexString(i));
      }
      result = buf.toString();
    } catch (NoSuchAlgorithmException e) {
      // ignore
    }
    return result;
  }

  @Component
  @ConfigurationProperties(prefix = "dapeng")
  static class DapengApi{
    private String uri;
    private String apiKey;

    public String getUri() {
      return uri;
    }

    public void setUri(String uri) {
      this.uri = uri;
    }

    public String getApiKey() {
      return apiKey;
    }

    public void setApiKey(String apiKey) {
      this.apiKey = apiKey;
    }
  }
}
